const useWS = require("./utils/server")
const startClient = require('./client/start.js')
const {infoStack} = require('./utils/stack.js')

const {terminal} = require('../config.json').server


const {anasysArgument} = require('./utils/arguments.js')
const originLog = console.log
const process = require('node:process');

let server = null

function useClientConsole(){
    return new Promise((resolve)=>{

        // 开启前端
        startClient(originLog)
        useWS(originLog, (ws) => {
            originLog('🔵 node-conosle => node已配置同步输出至浏览器端')
            server = ws
            resolve()
        })

        // 获取栈信息
        function getLogStack() {
            const stack = new Error().stack.replace('Error','Console')
            return stack
        }

        console.log = function () {
            try {
                // 原生console.log
                terminal && originLog( ...arguments) 
                // 记录log内容与堆栈,处理stack信息，过滤error字样，去除前两条栈信息
                let stack = getLogStack()
                stack = stack.split('\n').slice(3).join('\n')
                const message = {
                    ModeCode: 'console',
                    params:anasysArgument(arguments,originLog),
                    stack:infoStack(stack,originLog)
                }
                server && server.send(JSON.stringify(message))

            } catch(error) {
                originLog('转发console时发生错误', error)

            }
        }






        // // 未捕获的异常
        // process.on('uncaughtException', (error,origin) => {
        //     setTimeout(()=>{
        //     originLog('rejectionHandled',origin)

        //         // 处理error stack
        //         const stack = error.stack.split('\n').slice('1').join('\n')
        //         const data = error.stack.split('\n')[0]

        //         server.send(JSON.stringify({ ModeCode: 'error',  stack,data }))
        //     },0)


        // });

        

        
    })
}

function initConsole(main){
    useClientConsole().then(()=>{

        try{
            if(main && typeof main==='function'){
                main()
            }

        } catch(error){
            // 处理error stack
            const stack = error.stack.split('\n').slice('1').join('\n')
            const params = [error.stack.split('\n')[0]]

            const message ={
                ModeCode: 'error',
                params,
                stack:infoStack(stack,originLog)
            }
            server.send(JSON.stringify(message))
        }
    } )
}

module.exports = initConsole

